import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { captchaAPI } from "@/api";
import type { CaptchaResponseData } from "@/types/response";

// 验证码相关查询
export const useCaptcha = () => {
  return useQuery<CaptchaResponseData>({
    queryKey: ["captcha"],
    queryFn: async (): Promise<CaptchaResponseData> => {
      const response = await captchaAPI.generate("digit");
      return response.data;
    },
    staleTime: 5 * 60 * 1000, // 5分钟
    gcTime: 10 * 60 * 1000, // 10分钟
  });
};

export const useRefreshCaptcha = () => {
  const queryClient = useQueryClient();

  return useMutation<CaptchaResponseData, Error, void>({
    mutationFn: async (): Promise<CaptchaResponseData> => {
      const response = await captchaAPI.generate("digit");
      return response.data;
    },
    onSuccess: (data) => {
      // 更新验证码缓存
      queryClient.setQueryData(["captcha"], data);
    },
  });
};
